package zjy.android.radapter.adapter.factory;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import retrofit2.CallAdapter;
import retrofit2.Retrofit;
import zjy.android.radapter.adapter.LiveDataCallAdapter;
import zjy.android.radapter.livedata.ReturnLiveData;

/**
 * @Create zhang
 * @DATE 2021/7/27 0027
 * @DESC
 */
public final class LiveDataCallAdapterFactory extends CallAdapter.Factory {
    @Nullable
    @Override
    public CallAdapter<?, ?> get(@NonNull Type returnType, @NonNull Annotation[] annotations, @NonNull Retrofit retrofit) {
        if (getRawType(returnType) != ReturnLiveData.class) {
            return  null;
        }
        if (!(returnType instanceof ParameterizedType)) {
            throw new IllegalStateException("ReturnLiveData return type must be parameterized"
                    + " as ReturnLiveData<Foo> or ReturnLiveData<? extends Foo>");
        }
        Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType);
        return new LiveDataCallAdapter<>(responseType);
    }
}
